import React, { Component } from "react";

import { connect } from "react-redux";

const mapStateToProps = (state) => {
  return {
    list: state.get("list"),
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    add2(payload) {
      dispatch({ type: "add2", payload });
    },
    remove2(id) {
      dispatch({ type: "remove2", id });
    },
  };
};

@connect(mapStateToProps, mapDispatchToProps)
class TodoList extends Component {
  state = {
    textValue: "",
  };

  handleChange = (e) => {
    this.setState({
      textValue: e.target.value,
    });
  };

  handleClick = () => {
    this.props.add2({
      id: new Date().getTime(),
      name: this.state.textValue,
    });
  };

  render() {
    return (
      <>
        <input
          type="text"
          value={this.state.textValue}
          onChange={this.handleChange}
        />
        <button onClick={this.handleClick}>添加</button>
        <ul>
          {this.props.list.map((item) => (
            <li key={item.id}>
              {item.name} -{" "}
              <button onClick={() => this.props.remove2(item.id)}>删除</button>
            </li>
          ))}
        </ul>
      </>
    );
  }
}

export default TodoList;
